package com.feinno.urcs.group.siptask;

import com.feinno.urcs.group.servlet.GroupMemberDialog;
import com.feinno.urcs.group.servlet.GroupMemberDialogHasOffline;
import com.feinno.urcs.group.servlet.GroupServlet;
import com.feinno.urcs.group.siptask.task.GroupInviteArgs;
import com.feinno.urcs.group.siptask.task.GroupTaskEvents;
import org.helium.framework.annotations.FieldSetter;
import org.helium.framework.annotations.TaskImplementation;
import org.helium.framework.task.DedicatedTask;
import org.helium.framework.task.DedicatedTaskContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * AS 到 UE 的invite .
 * Created by Lei Gao on 5/8/15.
 */
@TaskImplementation(event = GroupTaskEvents.GROUP_INVITE)
public class GroupInviteTask implements DedicatedTask<GroupInviteArgs> {
	private static final Logger LOGGER = LoggerFactory.getLogger(GroupInviteTask.class);

	@FieldSetter("group:GroupServlet")
	private GroupServlet servlet;
	public static final String TASK_CONTEXT_NAME = "T";

	public GroupInviteTask() {

	}

	public GroupInviteTask(GroupServlet servlet) {
		this.servlet = servlet;
	}

	@Override
	public void processTask(DedicatedTaskContext ctx, GroupInviteArgs args) {
		try {
			if (args.isCancel()) {
				GroupMemberDialog memberDialog = (GroupMemberDialog) ctx.getSession(TASK_CONTEXT_NAME);
				if(memberDialog !=null ){
					memberDialog.cancel();
					memberDialog.setClean(true);
				}
			} else {
				servlet.inviteMemberDialog(args);
			}
		} catch (Exception e) {
			LOGGER.error(String.format("processTask error args=%s", args.toJsonObject().toString()), e);
		} finally {
			ctx.setTaskRunnable();
		}
	}


	@Override
	public void processTaskRemoved(DedicatedTaskContext ctx) {
		servlet.close(ctx);
	}
}
